package com.ruoyi.system.utils;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * 邮件发送工具类
 */
public class EmailUtil {

    // 邮件服务器配置（建议从配置文件中读取）
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final String SMTP_PORT = "587";
    private static final String SMTP_USERNAME = "1724705286@qq.com";
    private static final String SMTP_PASSWORD = "fiiejoefnzhvdcji";
    private static final boolean SMTP_SSL = true;

    /**
     * 发送带附件的邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件正文内容
     * @param attachmentPath 附件路径（可为null）
     * @throws MessagingException
     * @throws IOException
     */
    public static void sendEmailWithAttachment(String to, String subject, String htmlContent, String attachmentPath)
        throws MessagingException, IOException {

        // 1. 创建邮件会话
        Session session = createSession();

        // 2. 创建邮件消息
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(SMTP_USERNAME));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);

        // 3. 创建邮件内容（支持附件）
        MimeMultipart multipart = new MimeMultipart();

        // 添加HTML正文内容（关键修改）
        MimeBodyPart textPart = new MimeBodyPart();

        // 方法1：使用ByteArrayDataSource（推荐）
        textPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(htmlContent.getBytes(StandardCharsets.UTF_8),
                "text/html; charset=UTF-8"
            )));

        multipart.addBodyPart(textPart);

        // 添加附件（如果有）
        if (attachmentPath != null && !attachmentPath.isEmpty()) {
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.attachFile(new File(attachmentPath));
            multipart.addBodyPart(attachmentPart);
        }

        message.setContent(multipart);

        // 4. 发送邮件
        Transport.send(message);
    }

    /**
     * 创建邮件会话
     */
    private static Session createSession() {
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", String.valueOf(SMTP_SSL));

        return Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SMTP_USERNAME, SMTP_PASSWORD);
            }
        });
    }

    /**
     * 测试邮件发送
     */
    public static void main(String[] args) {
        try {
            sendEmailWithAttachment(
                "1264048157@qq.com",
                "测试邮件主题",
                "这是一封测试邮件内容。",
                "D:\\ruoyi\\uploadPath\\poPdf\\北芒建行对账单202506.pdf"
            );
            System.out.println("邮件发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("邮件发送失败: " + e.getMessage());
        }
    }
}
